import { contestsViews, questionsViews } from "@/models/views";
import axios from "axios";
import { globalUrl } from "./global";

async function toGetLatestContest(): Promise<contestsViews[] | null> {
    try {
        const res = await axios.get(globalUrl + 'sql/contests/gets?limit=5');
        const data: contestsViews[] = [];
        if (res.status == 200 && res.data.code == 0) {
            for(let i = 0; i < res.data.contest_.length; i++) {
                data.push({
                    contest_id: res.data.contest_[i].contest_id,
                    name: res.data.contest_[i].name
                })
            }
            return data;
        } else {
            return null;
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

async function toGetLatestQuestions(): Promise<questionsViews[] | null> {
    try {
        const res = await axios.get(globalUrl + 'sql/questions/gets?limit=5');
        const data: questionsViews[] = [];
        if (res.status == 200 && res.data.code == 0) {
            for(let i = 0; i < res.data.questions.length; i++) {
                data.push({
                    question_id: res.data.questions[i].Questions.question_id,
                    name: res.data.questions[i].Questions.name,
                    difficulty: res.data.questions[i].Questions.difficulty
                })
            }
            return data;
        } else {
            return null;
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

export { toGetLatestContest, toGetLatestQuestions }